  //jquery.CreativePlugins.js

  //last update: 18/01/13 - updated TimedGallery interval to 4000 

/*


****Plugins description

===> AsosGallery
      {creates a sliding gallery from a list within a container}
    [
      $(galleryClass).AsosGallery({animDuration:300, galleryContainer:_this.find('.gallery-container'), slideHolder:_this.find('.slide-holder'), slideClass:'.slide', slideSet:_this.find('.slide'), navNext:_this.find('.nav-next'), navBack:_this.find('.nav-back')});
      
      structure:
      <div class="gallery">
        <div class="gallery-container">
          <ul class="slide-holder">
            <li class="slide"><a href="#" title=""><img src="http://images.asos.com/htmlpages/" alt="" /></a></li>
            <li class="slide"><a href="#" title=""><img src="http://images.asos.com/htmlpages/" alt="" /></a></li>
            <... use as many list items as required ...>
          </ul>
        </div>
        <ul class="gallery-nav">
          <li><a class="nav nav-back" href="#">Back</a></li>
          <li><a class="nav nav-next" href="#">Next</a></li>
        </ul>
      </div>
    ]


===> AutoOver
      {when cerating a menu with links, automatically sets the link of class 'linksClass' of the current page to its rollover state (imageName.ext becomes imageName_over.ext) also removes the 'className' from the link to prevent any potential rollover effects}
    [
      $(linksClass).AutoOver({className: 'linksClass'});
    ]


===> ColorOverlay
      {creates an overlay above 'linksClass' of color 'color' and 'z-index 'zIndex'. The overlay has an opacity of 'opacityDefault' and fades on rollover to opacity 'opacityFadeTo' in 'duration' milliseconds}
    [
      $(linksClass).ColorOverlay({color:'white', opacityDefault:0, opacityFadeTo:0.2, duration:350, zIndex:1});
    ]


===> EnhanceClick
      {Makes a container clickable and linking to either the only contained link or a link defined by it's nth-child index. The link can also be set up to be opened in a new window}
    [
      $('containerClass').EnhanceClick({hrefNthChild:false, blank:false});
    ]


===> FadeOpacity
      {fades image in 'duration' milliseconds to 'opacity' opacity on 'roClass' mouseOver}
    [
      $(roClass).FadeOpacity({opacity:0.5, duration:305}); //default values
    ]


===> FadeRo
      {fades between two images (imageName.ext and imageName_over.ext) in 'speed' milliseconds on 'roClass' mouseOver}
    [
      $(roClass).FadeRo({speed:500}); //default value
    ]


===> HorizontalScroll
      {Scrolls the content of 'inputDiv' div horizontally of 'numOfPx' pixels each 'interval' milliseconds using 'leftBtn' and 'rightBtn' buttons}
    [
      $('#slider').HorizontalScroll({inputDiv:'#slider', leftBtn:'.left', rightBtn:'.right', interval:1, numOfPx:2}); //default values
    ]


===> ImageButton
      {switches between two images (imageName.ext and imageName_over.ext) on 'roClass' mouseOver}
      [
        $(roClass).ImageButton();
      ]

===> MouseScroll
      {Scrolls the content of 'sliderClass' div in 'type' direction (can be 'horizontal', 'vertical' or 'both') on mouseMove between 'stopSection' sections at a frame rate of 'frameRate' in 'speed' speed}
      [
        $(sliderClass).mousescroll({speed:5, stopSection:150, type: 'horizontal', frameRate:90}); //default values
      ]


===> TimedGallery
      {automatically fades images inside '#gallery' list in 'speed' milliseconds every 'interval' milliseconds, pausing on rollover if 'pause'}
      [
        $('#gallery').timedgallery({speed: 300, pause: true, interval: 4000}); //default values

      structure:
        <ul id="gallery">
          <li><img src="images/01.jpg" /></li>
          <li><img src="images/02.jpg" /></li>
        </ul>
      ]


===> VerticalScroll
      {Scrolls the content of 'inputDiv' div vertically of 'numOfPx' pixels each 'interval' milliseconds using 'upBtn' and 'downBtn' buttons}
      [
        $('#slider').HorizontalScroll({inputDiv:'#slider', upBtn:'.up', downBtn:'.down', interval:1, numOfPx:2}); //default values
      ]



****Functions description

===> function GetParameters(href)
      {returns an array of parameters contained in "href"}
    [
      array = GetParameters(http://www.asos.com/pgehtml.aspx?cid=11128&page=02)
      returns:
        array[cid] = 11128
        array[page] = 02
    ]

===> function RandomFromTo(from,to)
      {gets a random number between "from" and "to"}

*/




/*** Plugins ***/



////AsosGallery
  (function($)
  {
    $.fn.AsosGallery = function(opt)
    {
        var _this = $(this);
        var defaults = {
            animDuration:300,
            galleryContainer:_this.find('.gallery-container'),
            slideHolder:_this.find('.slide-holder'),
            slideClass:'.slide',
            slideSet:_this.find('.slide'),
            navNext:_this.find('.nav-next'),
            navBack:_this.find('.nav-back')
        };
        opt = $.extend(defaults, opt);

      return this.each(function()
      {
        //set slideholder width and scrollLeft
        opt.slideHolder.css({'width':parseInt(opt.slideSet.css('width'))*opt.slideSet.length + parseInt(opt.slideSet.css('marginRight'))*(opt.slideSet.length - 1)});
        opt.galleryContainer.scrollLeft(0);
        //caching
        var _activeElement = (opt.slideHolder.find('.active').length > 0) ? opt.slideHolder.find('.active') : opt.slideHolder.find(opt.slideClass+':first-child').addClass('active');
        var _galleryContainerWidth = parseInt(opt.galleryContainer.width());
        var _slideHolderWidth = opt.slideHolder.width();
        var _scrollLeft = 0;
        //functions
        function updateNav()
        {
          opt.navNext.show();
          opt.navBack.show();
          if(_activeElement.attr('class') == opt.slideHolder.find(opt.slideClass+':first').attr('class'))
            opt.navBack.hide();
          else if((_activeElement.attr('class') == opt.slideHolder.find(opt.slideClass+':last').attr('class')) || (_slideHolderWidth - _scrollLeft <= _galleryContainerWidth))
            opt.navNext.hide();
        }
        function scrollSlide()
        {
          _scrollLeft = parseInt(opt.galleryContainer.scrollLeft()) + parseInt(_activeElement.position().left);
          opt.galleryContainer.stop(true).animate({'scrollLeft':_scrollLeft},opt.animDuration);
          updateNav();
        }
        function scrollNext(e)
        {
          e.preventDefault();
          _activeElement = _activeElement.removeClass('active').next().addClass('active');
          scrollSlide();
        }
        function scrollBack(e)
        {
          e.preventDefault();
          _activeElement = _activeElement.removeClass('active').prev().addClass('active');
          scrollSlide();
        }
        //update nav
        updateNav();
        //window load - attach events
        $(window).load(function()
        {
          opt.navNext.bind('click',scrollNext);
          opt.navBack.bind('click',scrollBack);
        });
      });
    };
  })(jQuery);
  
////AutoOver
  (function($)
  {
    $.fn.AutoOver = function(opt)
    {
      var defaults = {
          className:''
      };

      var options = $.extend(defaults, opt);

      var currentURL = window.location.href;
      var parameters = GetParameters(document.location.href);
      var currentCid = parameters['cid'];

      var className = options.className;

      $(this).each(function()
      {
        var currentRO = $(this).attr('href');
        var parameters = GetParameters(currentRO);

        if(currentCid && currentCid == parameters['cid'])
        {
          var src = $(this).find('img').attr('src');
          var aSrc = src.split('.');
          var srcBase = '';
          var i;
          for(i=0;i<aSrc.length-1;i++)
          {
            srcBase += aSrc[i]+'.';
          }
          srcBase = srcBase.slice(0,srcBase.length-1);
          $(this).find('img').attr('src',srcBase+"_over."+aSrc[aSrc.length-1]);
          $(this).removeClass(className);
        }
      });
    };
  })(jQuery);




////ColorOverlay
  (function($)
  {
    $.fn.ColorOverlay = function(opt)
    {
        var defaults = {
          color:'white',
          opacityDefault:0,
          opacityFadeTo:0.2,
          duration:350,
          zIndex:1
        };

        var options = $.extend(defaults, opt);

        //generate a random key to keep the divs unique within each plugin call
        var randomKey=Math.floor(Math.random()*100001);

        //for each element of targeted class
        $(this).each(function()
        {
          //create a div overlay matching target position and dimentions using the key
          $(this).parent().append("<div class='divColorOverlayJQuery"+randomKey+"' id='"+$(this).attr('href')+"' style='width:"+$(this).width()+"px; height:"+$(this).height()+"px; left:"+$(this).position().left+"px; top:"+$(this).position().top+"px;'>&nbsp;</div>");
        });

        //for each created overlays containing the key, set position to absolute and assign 'zIndex' and 'opacityDefault' parameters
        $('.divColorOverlayJQuery'+randomKey).css({'position':'absolute','zIndex':options.zIndex,'backgroundColor':options.color,'opacity':options.opacityDefault,'cursor':'pointer'}).hover(
        function()
        {
          //on rollover, fade to 'opacityFadeTo'
          $(this).stop(true).animate({'opacity':options.opacityFadeTo},350);
        },
        function()
        {
          //on rollout, fade to 'opacityDefault'
          $(this).stop(true).animate({'opacity':options.opacityDefault},350);
        }).click(
        function()
        {
          //redirect to id value onclick
          window.location.href = $(this).attr('id');
        });
    };
  })(jQuery);




////EnhanceClick
  (function($)
  {
    $.fn.EnhanceClick = function(opt)
    {
        var defaults = {
            hrefNthChild:false,
            blank:false
        };
        opt = $.extend(defaults, opt);

      return this.each(function()
      {
        var _this = $(this);
        function enhance()
        {
          var _anchor;
          if(!opt.hrefNthChild)
            _anchor = _this.find('a').attr('href');
          else
            _anchor = _this.find('a:nth-child('+parseInt(opt.hrefNthChild)+')').attr('href');
          if(!opt.blank)
            window.location.href = _anchor;
          else
            window.open(_anchor);
        }
        _this.find('a').click(function(e){e.preventDefault();});
        _this.bind('click',enhance);
      });
    };
  })(jQuery);




////FadeOpacity
  (function($)
  {
    $.fn.FadeOpacity = function(opt)
    {
        var defaults = {
            opacity:0.5,
            duration:305
        };

        var options = $.extend(defaults, opt);
      $(this).each(function()
        {
          var _this = $(this);
          var defaultOpacity = _this.css('opacity');

          _this.mouseover(function()
          {
            //animate target to opacity 'opacity' in 'duration' milliseconds
            _this.stop(true).animate({opacity:options.opacity},{duration:options.duration});
          });

          _this.mouseout(function()
          {
            //animate target to opacity 1 in 'duration' milliseconds
            _this.stop(true).animate({opacity:defaultOpacity},{duration:options.duration});
          });
        });
    };
  })(jQuery);




////FadeRo
  (function($)
  {
    $.fn.FadeRo = function(opt)
    {
      var defaults = {
        speed: 500
      }

      var options = $.extend(defaults, opt);
      var speed = options.speed;

      $(this).hover(function()
      {
        var thisImage = $(this).find("img");
        var thisSrc = thisImage.attr("src").split('/');
        var preImgSrc = "";
        var i;
        for(i=0; i<thisSrc.length-1; i++)
        {
          preImgSrc += thisSrc[i]+'/';
        }
        var imgSrc = thisSrc[thisSrc.length-1].split('.');

        var overSrc = preImgSrc+imgSrc[0]+"_over."+imgSrc[1];

        if($(this).find("img.overImg").length == 0)
        {
          $(document.createElement("img")).attr({ src: overSrc}).css({"position":"absolute","left":0,"top":0,"opacity":0}).addClass("overImg").appendTo($(this));
        }

        $(this).find("img.overImg").stop(true).animate({"opacity":"1"},speed, function(){$(this).find("img:first").css({"opacity":"0"});});
      },
      function()
      {
        $(this).find("img.overImg").stop(true).animate({"opacity":"0"},speed, function(){$(this).find("img:first").css({"opacity":"1"});});
      });
    };
  })(jQuery);




////HorizontalScroll
  (function($)
  {
    $.fn.HorizontalScroll = function(opt)
    {
      var defaults = {
        inputDiv: "#slider",
        leftBtn: ".left",
        rightBtn: ".right",
        interval: 1,
        numOfPx: 2
      };

      var options = $.extend(defaults, opt);
      var inputDiv = options.inputDiv;
      var leftBtn = options.leftBtn;
      var rightBtn = options.rightBtn;
      var interval = options.interval;
      var numOfPx = options.numOfPx;

      var move = false;
      var timer;

      $(leftBtn).hover(function()
      {
        move = "left";
      },
      function()
      {
        clearInterval(timer);
        move = false;
      });

      $(rightBtn).hover(function()
      {
        move = "right";
      },
      function()
      {
        clearInterval(timer);
        move = false;
      });

      timer = setInterval(animateDiv, interval);

      function animateDiv()
      {
        if (move == "left")
          $(inputDiv).attr('scrollLeft',$(inputDiv).attr('scrollLeft') - numOfPx);
        else if (move == "right")
          $(inputDiv).attr('scrollLeft',$(inputDiv).attr('scrollLeft') + numOfPx);
        else
          return null;
      }
    }
  })(jQuery);




////ImageButton
  (function($)
  {
    $.fn.ImageButton = function()
    {
      var currentImg = $(this).find('img');
      $(this).find('img').css({cursor: 'pointer'});

      $(currentImg).hover(function()
      {
        var thisSrc = this.src.split('/');
        var preImgSrc = "";
        var i;
        for(i=0; i<thisSrc.length-1; i++)
        {
          preImgSrc += thisSrc[i]+'/';
        }
        var imgSrc = thisSrc[thisSrc.length-1].split('.');

        $(this).attr("src",preImgSrc+imgSrc[0]+"_over."+imgSrc[1]);
      },
      function()
      {
        var thisSrc = this.src.split('/');
        var preImgSrc = "";
        var i;
        for(i=0; i<thisSrc.length-1; i++)
        {
          preImgSrc += thisSrc[i]+'/';
        }
        var imgSrc = thisSrc[thisSrc.length-1].split('.');

        $(this).attr("src",preImgSrc+imgSrc[0].slice(0, -5)+"."+imgSrc[1]);
      });
    };
  })(jQuery);




////MouseScroll
  (function($)
  {
    var type;
    var speed;
    var stopSection;
    var frameRate;
    var conWidth;
    var conHeight;

    $.fn.mousescroll = function(opt)
    {
        var defaults = {
        speed: 5,
        stopSection: 150,
        type: "horizontal",
        frameRate: 90
        };

      var options = $.extend(defaults, opt);
      speed = options.speed;
      stopSection = options.stopSection;
      type = options.direction;
      frameRate = options.frameRate;
      var inputDiv = $(this);

      var move = false;

      $(this).bind("mouseenter", function(e)
      {
        move = true;
      });

      $(this).bind("mouseleave", function(e)
      {
        move = false;
      });

      $(this).css({overflow: 'hidden'});
      conWidth = parseInt($(this).css('width'));
      conHeight = parseInt($(this).css('height'));

      var currentY;
      var currentX;

      $(this).mousemove(function(e)
      {
        currentY = e.pageY - $(this).offset().top;
        currentX = e.pageX - $(this).offset().left;
      });

      var lessThanY = parseInt($(this).css('height'))/2 - stopSection/2;
      var moreThanY = parseInt($(this).css('height'))/2 + stopSection/2;
      var lessThanX = parseInt($(this).css('width'))/2 - stopSection;
      var moreThanX = parseInt($(this).css('width'))/2 + stopSection;

      function enterFrame()
      {
        if(move){
          if(currentX < lessThanX)
            scrollContainerX(-1, (lessThanX - currentX)/lessThanX);
          else if(currentX > moreThanX)
            scrollContainerX(1, (currentX - moreThanX)/(conWidth - moreThanX));
          else
            scrollContainerX(0, 0);

          if(currentY < lessThanY)
            scrollContainerY(-1, (lessThanY - currentY)/lessThanY);
          else if(currentY > moreThanY)
            scrollContainerY(1, (currentY - moreThanY)/(conHeight - moreThanY));
          else
            scrollContainerY(0, 0);
        }
      }
      var timer = setInterval(enterFrame, 1000/frameRate);

      function scrollContainerY(direction, acc)
      {
        if(type == "vertical" || type == "both")
          inputDiv.attr('scrollTop', inputDiv.attr('scrollTop') + (direction * speed)*acc);
      }

      function scrollContainerX(direction, acc)
      {
        if(type == "horizontal" || type == "both")
          inputDiv.attr('scrollLeft',inputDiv.attr('scrollLeft') + (direction * speed)*acc);
      }
    }
  })(jQuery);




////TimedGallery
  (function($)
  {
    var images;
    var speed;
    var currentPage;
    var over;

    $.fn.timedgallery = function(opt)
    {
        var defaults = {
            speed: 300,
        pause: true,
        interval: 4000
        };

      images = $(this).children();

      var options = $.extend(defaults, opt);
        speed = options.speed;
      interval = options.interval;
      pause = options.pause;

      $(images).each(function()
      {
        $(this).css({position: "absolute", top: 0, left: 0});
        $(this).hide();
      });

      changePage(0);

      var timer = setInterval(nextPage, interval);

      $(this).hover
      (
        function()
        {
          over = true;
        },
        function()
        {
          over = false;
        }
      )
    };

    function nextPage()
    {
      if(currentPage + 1 > $(images).length - 1)
        changePage(0);
      else
        changePage(currentPage + 1);
    }

    function changePage(image)
    {
      if(!pause || !over)
      {
        $(images).each(function()
        {
          $(this).fadeOut(speed);
        });
        $(images[image]).fadeIn(speed);

        currentPage = image;
      }
    }

  })(jQuery);




////VerticalScroll
  (function($)
  {
    $.fn.VerticalScroll = function(opt)
    {
      var defaults = {
        inputDiv: "#slider",
        upBtn: ".up",
        downBtn: ".down",
        interval: 1,
        numOfPx: 2
      };

      var options = $.extend(defaults, opt);
        inputDiv = options.inputDiv;
        upBtn = options.upBtn;
        downBtn = options.downBtn;
        interval = options.interval;
        numOfPx = options.numOfPx;

      var move = false;
      var timer;

      $(upBtn).hover(function()
      {
        move = "up";
      },
      function()
      {
        clearInterval(timer);
        move = false;
      });

      $(downBtn).hover(function()
      {
        move = "down";
      },
      function()
      {
        clearInterval(timer);
        move = false;
      });

      timer = setInterval(animateDiv, interval);

      function animateDiv()
      {
        if (move == "up")
          $(inputDiv).attr('scrollTop',$(inputDiv).attr('scrollTop') - numOfPx);
        else if (move == "down")
          $(inputDiv).attr('scrollTop',$(inputDiv).attr('scrollTop') + numOfPx);
        else
          return null;
      }
    };
  })(jQuery);




 /*** Functions ***/




////GetParameters
  function GetParameters(href)
  {
    var arg = new Object();

    if ( href.indexOf( "?") != -1)
    {
      var params = href.split( "?")[1];
      var param = params.split("&");

      for (var i = 0; i < param.length; ++i)
      {
        var name = param[i].split("=")[0];
        var value = param[i].split("=")[1];

        arg[name] = value;
      }
    }
    return arg;
  }




////RandomFromTo
  function RandomFromTo(from, to)
  {
    return Math.floor(Math.random() * (to - from + 1) + from);
  }




/*** Prototype Override ***/




////Fix IE text fade issues
  (function($)
  {
    $.fn.fadeIn = function(speed, callback) {
        return this.animate({opacity: 'show'}, speed, function() {
                if ( $.browser.msie )
                        this.style.removeAttribute('filter');
                if ( $.isFunction(callback) )
                        callback.call(this);
        });
    };

    $.fn.fadeOut = function(speed, callback) {
        return this.animate({opacity: 'hide'}, speed, function() {
                if ( $.browser.msie )
                        this.style.removeAttribute('filter');
                if ( $.isFunction(callback) )
                        callback.call(this);
        });
    };

    $.fn.fadeTo = function(speed, to, callback) {
        return this.animate({opacity: to}, speed, function() {
                if ( to == 1 && $.browser.msie )
                        this.style.removeAttribute('filter');
                if ( $.isFunction(callback) )
                        callback.call(this);
        });
    };
  })(jQuery);